package com.example.spring_transaction.controller;

import com.example.spring_transaction.service.LogService;
import com.example.spring_transaction.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @className: TestController
 * @author: 芃
 * @description: 编程式事务
 * @date: 2024/12/30 17:40
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
    @Autowired
    private UserService userService;

    @Autowired//事务管理器
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private LogService logService;

    @RequestMapping("/registry")
    public String registry(String userName,String password){
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        Integer result =  userService.addUser(userName,password);
        if (result == 1){
            log.info("User added successfully");
            //提交事务
            dataSourceTransactionManager.commit(transaction);
            return "注册成功";
        }else {
            log.info("User added failed");
            //回滚事务
            dataSourceTransactionManager.rollback(transaction);
            return "注册失败";
        }
    }
}
